# -*- coding: utf-8 -*-
from flask import Flask, render_template, jsonify, send_from_directory
import os
import time
import utils
import threading

app = Flask(__name__)
app.secret_key = 'secret'

ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
IMAGE_NAME = 'image.jpg'
IMAGE_PATH = os.path.join(ROOT_DIR, IMAGE_NAME)

@app.route('/')
def index():
    image_exists = os.path.isfile(IMAGE_PATH)
    return render_template('index.html',
                           image_exists=image_exists,
                           image_url='/image.jpg' if image_exists else None,
                           label='')

@app.route('/image.jpg')
def serve_image():
    x= send_from_directory(ROOT_DIR, IMAGE_NAME)
    print(x)
    return x

@app.route('/api/refresh_image')
def refresh_image():
    # 仅刷新图片
    try:
        utils.get_image()
    except Exception as e:
        print('get_image 调用失败:', e)
    if os.path.isfile(IMAGE_PATH):
        ts = int(os.path.getmtime(IMAGE_PATH))
        return jsonify({
            'image_url': '/image.jpg?ts=' + str(ts),
            'timestamp': ts
        })
    else:
        return jsonify({
            'image_url': None,
            'timestamp': int(time.time())
        })

@app.route('/api/get_label')
def get_label():
    # 单独获取标签
    label = ''
    if os.path.isfile(IMAGE_PATH):
        try:
            label = utils.detect() or ''
        except Exception as e:
            print('detect 调用失败:', e)
            label = ''
    return jsonify({'label': label})

@app.route('/api/alarm', methods=['POST'])
def trigger_alarm():
    try:
        threading.Thread(target=utils.alarm, daemon=True).start()
        return jsonify({'ok': True})
    except Exception as ex:
        print('alarm 异步调用失败:', ex)
        return jsonify({'ok': False, 'error': str(ex)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)